package com.lbd.gulimall.product.exception;

import com.lbd.common.exception.BizCodeEnum;
import com.lbd.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: gulimall
 * @Package: com.lbd.gulimall.product.exception
 * @ClassName: ExceptionHandler
 * @Author: linbd
 * @Description: 异常处理器
 * @Date: 2021/6/14 17:12
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.lbd.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    /**
     * JSR303异常处理器
     *
     * @param e: 参数校验异常类
     * @return:
     * @author: linbd
     * @date: 2021/6/14 17:48
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleArgumentException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            String fieldName = fieldError.getField();
            String value = fieldError.getDefaultMessage();
            map.put(fieldName,value);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 如果上面的异常处理器都没有匹配到就会走最大的异常
     *
     * @param e:
     * @return:
     * @author: linbd
     * @date: 2021/6/14 17:49
     */
    /*@ExceptionHandler(value = Throwable.class)
    public R handleArgumentException(Throwable e) {
        log.error(e.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }*/
}
